package com.sysu.simulation;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.TextInputLayout;

import android.support.v4.content.SharedPreferencesCompat;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;

import android.view.View;

import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sysu.simulation.bean.User;
import com.sysu.simulation.helper.AccountHelper;
import com.sysu.simulation.helper.ApiHelper;
import com.sysu.simulation.helper.NetworkHelper;
import com.sysu.simulation.widget.BottomPasswordDialog;

import butterknife.BindView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class LoginActivity extends BaseActivity implements View.OnClickListener, View.OnFocusChangeListener {

    private ProgressDialog mDialog;
    private BottomPasswordDialog mBottomDialog;
    private Toast mToast;
    private static final String PREF_NAME = "HOLD_ACCOUNT";
    private static final String UID_KEY_NAME = "hold_Uid";

    @BindView(R.id.account)
    EditText account_text;
    @BindView(R.id.password)
    EditText pwd_text;
    @BindView(R.id.account_layout)
    TextInputLayout account_layout;
    @BindView(R.id.password_layout)
    TextInputLayout pwd_layout;
    @BindView(R.id.sign_in_button)
    Button sign_in_button;
    @BindView(R.id.register_button)
    Button register_button;
    @BindView(R.id.login_progress)
    ProgressBar mBar;

    @Override
    protected int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    protected void initWindow() {
        super.initWindow();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(false);
        }
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        account_text.setOnFocusChangeListener(this);
        pwd_text.setOnFocusChangeListener(this);
        initBottomDialog();
    }

    private void initBottomDialog() {
        mBottomDialog = BottomPasswordDialog.getDialog(this);

        mBottomDialog.setSubmitListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String pwd1 = pwd_text.getText().toString().trim();
                String pwd2 = mBottomDialog.getEditText().getText().toString().trim();
                if(pwd1.equals(pwd2)) {
                    String uid = account_text.getText().toString().trim();
                    mBottomDialog.dismiss();
                    doRegister(uid,pwd2);
                }
                else showToast("密码不一致。");
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        SharedPreferences sp = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        String holdUid = sp.getString(UID_KEY_NAME, null);
        account_text.setText(holdUid);
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return super.onSupportNavigateUp();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    public static void show(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onFocusChange(View v, boolean isFocus) {
        int id = v.getId();
        switch (id) {
            case R.id.account_layout:
                if(isFocus) {
                    account_layout.setActivated(true);
                    pwd_layout.setActivated(false);
                }
                break;
            case R.id.password_layout:
                if(isFocus) {
                    account_layout.setActivated(false);
                    pwd_layout.setActivated(true);
                }
                break;
        }
    }

    @OnClick({R.id.account, R.id.password, R.id.sign_in_button, R.id.register_button})
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.account:
                pwd_text.clearFocus();
                account_text.setFocusableInTouchMode(true);
                account_text.requestFocus();
                break;
            case R.id.password:
                account_text.clearFocus();
                pwd_text.setFocusableInTouchMode(true);
                pwd_text.requestFocus();
                break;
            case R.id.sign_in_button:
                attemptLogin();
                break;
            case R.id.register_button:
                attemptRegister();
                break;
            default:
                break;
        }
    }

    private void attemptLogin() {
        account_text.setError(null);
        pwd_text.setError(null);

        String uid = account_text.getText().toString().trim();
        String pwd = pwd_text.getText().toString().trim();

        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(pwd)) {
            pwd_text.setError(getString(R.string.error_field_required));
            focusView = pwd_text;
            cancel = true;
        }

        if (TextUtils.isEmpty(uid)) {
            account_text.setError(getString(R.string.error_field_required));
            focusView = account_text;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            if(NetworkHelper.hasInternet(this)) {
                doLogin(uid, pwd);
            }
            else {
                showToast("未连接网络");
            }
        }
    }

    /*private boolean isIdValid(String uid) {
        //TODO: Replace this with your own logic
        return true;
    }*/

    /*private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return true;
    }*/

    private void doLogin(String uid, String pwd) {
        ApiHelper.login(uid, pwd, new TextHttpResponseHandler() {

            @Override
            public void onStart() {
                super.onStart();
                showProgressBar("正在登录...");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                hideProgressBar();
            }

            @Override
            public void onCancel() {
                super.onCancel();
                hideProgressBar();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast("网络请求错误，请重试。");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if(responseString.equals("failed")) {
                    showToast("账号或密码有误，请重试。");
                    return;
                }

                try {
                    Gson gson = new Gson();
                    User currentUser = gson.fromJson(responseString, User.class);
                    String uid = account_text.getText().toString().trim();
                    currentUser.setId(uid);
                    if (AccountHelper.login(currentUser, headers)) {
                        saveLocalAccount(uid);
                        finish();
                    } else {
                        showToast("登录失败，请重试。");
                    }
                } catch(Exception e) {
                    showToast("解析错误，请重试。");
                }
            }
        });
    }

    private void saveLocalAccount(String uid) {
        if (!TextUtils.isEmpty(uid)) {
            SharedPreferences sp = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(UID_KEY_NAME, uid);
            SharedPreferencesCompat.EditorCompat.getInstance().apply(editor);
        }
    }

    private void attemptRegister() {
        account_text.setError(null);
        pwd_text.setError(null);

        String uid = account_text.getText().toString().trim();
        String pwd = pwd_text.getText().toString().trim();

        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(pwd)) {
            pwd_text.setError(getString(R.string.error_field_required));
            focusView = pwd_text;
            cancel = true;
        }

        if (TextUtils.isEmpty(uid)) {
            account_text.setError(getString(R.string.error_field_required));
            focusView = account_text;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            mBottomDialog.show();
        }
    }

    private void doRegister(String uid, String pwd) {
        if(!NetworkHelper.hasInternet(this)) {
            showToast("未连接网络");
            return;
        }

        ApiHelper.register(uid, pwd, new TextHttpResponseHandler() {

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast("注册失败，请重试。");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if(responseString.equals("failed")) {
                    showToast("账号已被使用，请重试。");
                    return;
                }
                attemptLogin();
            }
        });
    }

    private void showProgressBar(String msg) {
        if(mDialog==null) {
            mDialog = new ProgressDialog(this);
            mDialog.setCancelable(false);
            mDialog.setMessage(msg);
        }
        mDialog.show();
    }

    private void hideProgressBar() {
        ProgressDialog tmp = mDialog;
        if(mDialog!=null) {
            mDialog = null;
            try {
                tmp.cancel();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void showToast(String msg) {
        if(mToast==null) {
            mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        }
        mToast.setText(msg);
        mToast.show();
    }
}

